package com.demo.config;

import java.net.InetAddress;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.github.xiaoymin.knife4j.spring.configuration.Knife4jProperties;
import com.google.common.collect.Lists;

import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Knife4j配置
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class Knife4jConfig implements ApplicationListener<WebServerInitializedEvent> {

    private static Logger log = LoggerFactory.getLogger(Knife4jConfig.class);

    @Bean(value = "Knife4jCommon")
    public Docket createRestAdmin(@Autowired Knife4jProperties knife4jProperties) {
        // 添加请求参数，我们这里把token作为请求头部参数传入后端(defaultValue还不能使用具体问题不祥)
        RequestParameter parameter = new RequestParameterBuilder().name("Authorization").description("请求头token")
            .in(ParameterType.HEADER).query(x -> x.defaultValue("Bearer ")).build();
        List<RequestParameter> parameters = Lists.newArrayList();
        parameters.add(parameter);
        return new Docket(DocumentationType.SWAGGER_2).enable(true).useDefaultResponseMessages(false)
            .groupName(knife4jProperties.getDocuments().get(0).getGroup())
            .apiInfo(apiInfo(knife4jProperties.getDocuments().get(0).getName())).globalRequestParameters(parameters)
            .select().apis(RequestHandlerSelectors.withClassAnnotation(io.swagger.annotations.Api.class))
            .paths(PathSelectors.any()).build();

    }

    private ApiInfo apiInfo(String title) {
        return new ApiInfoBuilder().title(title).build();
    }

    /**
     * @see org.springframework.boot.ansi.AnsiColor.RED
     */
    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            log.info("项目启动成功！接口文档地址: http://{}:{}{}/doc.html", inetAddress.getHostAddress(),
                event.getWebServer().getPort(),
                event.getApplicationContext().getEnvironment().getProperty("server.servlet.context-path"));
        } catch (Exception e) {
            log.error("Knife4J error,", e);
        }
    }

}